package org.jetnuke.modules.content;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.VelocityContext;
import org.jetnuke.common.ActionForward;
import org.jetnuke.common.IAction;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IModuleInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.dao.DataAccessDriver;
import org.jetnuke.dao.PagesDAO;
import org.jetnuke.entities.Pages;
import org.jetnuke.entities.PagesCategories;

public class ShowPage implements IAction {

	int pid;
	int npage=0;

	public ActionForward exec(HttpServletRequest request,
			HttpServletResponse response, VelocityContext vc, IModuleInfo info,
			String op, IUserInfo ui, IAdminInfo ai) throws Exception {

		String template = "page.vm";
		PagesDAO pm=DataAccessDriver.getInst().newPagesDAO();
		Pages pg = DataAccessDriver.getInst().newPagesDAO().retrieveByPK(pid);// pagesPeer.retrieveByPK(pid);
		
		if (pg == null || pg.getACTIVE() == 0 /* && isNotAdministrator */) {
			template = "pageNotFound.vm";
		} else {
			PagesCategories cat = DataAccessDriver.getInst().newPagesCatDAO().retrieveByPK(pg.getCID());
			
			vc.put("cat",cat);
			vc.put("page", pg);
			String splitPages[]=pg.getTEXT().split("<!--pagebreak-->");
			int pageCount=splitPages.length;
			if(npage<1)
				npage=1;
			if(npage>pageCount)
				npage=pageCount;
			
			if(npage==1){
				pg.setCOUNTER(pg.getCOUNTER()+1);
				pm.update(pg);
				//pg.save();
			}
			vc.put("pageCount",new Integer(pageCount));
			vc.put("npage",new Integer(npage));
			vc.put("text",splitPages[npage-1]);
			
		}
		return new ActionForward(info, template);
	}

	public void setPid(int pid) {
		this.pid = pid;
	}
	/**
	 * @param page The page to set.
	 */
	public void setNpage(int npage) {
		this.npage = npage;
	}
}
